package com.indusfo.spc.controller;

import com.indusfo.spc.aspect.SystemControllerLog;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.interceptor.UserThreadLocal;
import com.indusfo.spc.pojo.Dep;
import com.indusfo.spc.pojo.ExcelErrorData;
import com.indusfo.spc.pojo.Role;
import com.indusfo.spc.pojo.User;
import com.indusfo.spc.service.DepService;
import com.indusfo.spc.service.UserService;
import com.indusfo.spc.untlis.CryptoUtils;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息控制器层
 *
 * @author xiet 2018年11月23日 下午2:41:25
 */
@Slf4j
@Controller
@RequestMapping("/service/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
  private DepService depService;


	/**
	 * 删除用户信息删除接口
	 * 
	 * @param userIds
	 * @return
	 */
	@RequestMapping(value = "/deleteUser")
	@SystemControllerLog(description="删除用户信息")
	@ResponseBody
	public JSONObject deleteUser(Integer[] userIds) {
		int dataState = 2;
		JSONObject json = userService.deleteUser(userIds, dataState);
		// 没有异常，正常返回数据给前端
		return json;
	}

	/**
	 * 启停接口
	 * @Title: UserController
	 * @param userIds
	 * @param dataState
	 * @return
	 */
	@RequestMapping(value = "/definesUser")
	@SystemControllerLog(description="启停用户信息")
	@ResponseBody
	public JSONObject definesUser(Integer[] userIds, Integer dataState) {
		JSONObject json = userService.deleteUser(userIds, dataState);
		// 没有异常，正常返回数据给前端
		return json;
	}
	
	/**
	 *	 新增用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/insertUser")
	@SystemControllerLog(description="新增用户信息")
	@ResponseBody
	public JSONObject insertUser(User user) {
    user.setSalt(CryptoUtils.randomSalt());
    user.setUserPwd(userService.encryptPassword(user.getUserCode(), user.getUserPwd(), user.getSalt()));
		JSONObject json = userService.insertUser(user);
		return json;
	}
	
	/**
	 * 	修改用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUser")
	@SystemControllerLog(description="修改用户信息")
	@ResponseBody
	public JSONObject updateUser(User user) {
		JSONObject json  = userService.updateUser(user);
		return json;
	}
	
	/**
	 * 	查询用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping("/queryUser")
	@SystemControllerLog(description="查询用户信息")
	@ResponseBody
	public JSONObject queryUser(User user) {
		JSONObject jsonObject = userService.queryUser(user);
		return jsonObject;
	}

	/**
	 * 	查询用户信息   (用户表  部门表)
	 * @param user
	 * @return
	 */
	@RequestMapping("/queryUserDep")
	@SystemControllerLog(description="查询用户信息")
	@ResponseBody
	public JSONObject queryUserDep(User user) {
		JSONObject jsonObject = userService.queryUserDep(user);
		return jsonObject;
	}


	/**
	 * @Description: 获取当前线程用户
	 * @Params: []
	 * @Returns: com.indusfo.spc.vo.JSONObject
	 * @author: 余家能
	 * @date: 2019/2/25 3:09 PM
	 */
	@RequestMapping("/getThreadUser")
	@ResponseBody
	public JSONObject getThreadUserName(){
		JSONObject jsonObject = new JSONObject();
		try {
			User user = UserThreadLocal.get();
			jsonObject.victroy("获取当前用户成功！",user);
		}catch (Exception e){
			jsonObject.defeated("获取当前用户失败！");
			log.error("未知错误!",e);
		}
		return jsonObject;
	}

    /**
     * 通过角色ID查询该角色未设置的用户（角色）
     *
     * @param role
     * @return com.indusfo.spc.vo.JSONObject
     * @author xuz
     * @date 2019/7/17 3:41 PM
     */
    @RequestMapping("/selectByRole")
    @ResponseBody
    public JSONObject selectByRole(Role role) {
        return userService.selectByRole(role);
    }

  /**
   * 重置密码
   *
   */
    @RequestMapping("/resetPwd")
    @ResponseBody
    public JSONObject resetPwd(User user){
      user.setSalt(CryptoUtils.randomSalt());
      user.setUserPwd(userService.encryptPassword(user.getUserCode(), user.getUserPwd(), user.getSalt()));
      return userService.resetPwd(user);
    }


  @RequestMapping("/uploadFileUser")
  @ResponseBody
  public JSONObject uploadFileUser(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws Exception {
    //定义一个message对象用于向前台传输数据
    JSONObject jsonObject = new JSONObject();
    jsonObject.setStatus(JSONObject.SUCCESS);
    //设置错误集合的
    List<ExcelErrorData> errorDatas = new ArrayList<>();
    response.setContentType("text/html;charset=UTF-8");
    //判断上传文件格式是否正确
    Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
    if (wb == null) {
      jsonObject.setStatus(JSONObject.ERROR);
      errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
    } else {
      //获取excel文件的第一个sheet
      Sheet sheet = wb.getSheetAt(0);
      if (sheet == null) {
        jsonObject.setStatus(JSONObject.ERROR);
        errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
      } else {
        //获取最后一行的行号
        int rowCount = sheet.getLastRowNum();
        if (rowCount < 1) {
          jsonObject.setStatus(JSONObject.ERROR);
          errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
        } else {
          List<User> addUser = new ArrayList<>();
          for (int i = 1; i <= rowCount; i++) {
            boolean needAdd = true;
            //获取到每一行的每一列的数据
            String userCode = ExcelUtil.getCellValue(sheet, i, 0, false);
            String userName = ExcelUtil.getCellValue(sheet, i, 1, false);
            String depName = ExcelUtil.getCellValue(sheet, i, 2, false);
            String userPwd = ExcelUtil.getCellValue(sheet, i, 3, false);
            int m = i + 1;
            //将excel中的每一行数据存储进行检查
           if(StringUtils.isBlank(userCode)){
             needAdd = false;
             jsonObject.setStatus(JSONObject.ERROR);
             errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第1列[登录账号]不能为空"));

           }else{
               if(userCode.getBytes().length>50){
                   needAdd = false;
                   jsonObject.setStatus(JSONObject.ERROR);
                   errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第1列[登录账号]长度不能超过50个字节,25个汉字"));
               }
              User user = userService.selectUserBycode(userCode);
              if(user != null){
                needAdd = false;
                jsonObject.setStatus(JSONObject.ERROR);
                errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第1列[登录账号]数据库已存在"));
              }
           }
            if(StringUtils.isBlank(userName)){
              needAdd = false;
              jsonObject.setStatus(JSONObject.ERROR);
              errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第2列[用户名称]不能为空"));
            }else if(userName.getBytes().length>50){
              needAdd = false;
              jsonObject.setStatus(JSONObject.ERROR);
              errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第2列[用户名称]长度不能超过50个字节,25个汉字"));
            }
            Integer depId = 0;
            if(StringUtils.isBlank(depName)){
              needAdd = false;
              jsonObject.setStatus(JSONObject.ERROR);
              errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第3列[用户部门]不能为空"));
            }else{
              List<Dep> deps = depService.selectDepByName(depName);
              if(deps.isEmpty()){
                needAdd = false;
                jsonObject.setStatus(JSONObject.ERROR);
                errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第3列[用户部门]数据库中不存在"));
              }else{
                depId = deps.get(0).getDepId();
              }
            }
            if(StringUtils.isBlank(userPwd)){
              needAdd = false;
              jsonObject.setStatus(JSONObject.ERROR);
              errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第4列[密码]不能为空"));
            }else if(userPwd.getBytes().length>18 || userPwd.getBytes().length<6){
                needAdd = false;
                jsonObject.setStatus(JSONObject.ERROR);
                errorDatas.add(ExcelErrorData.getExcelErrorData(m, "第4列[密码]“密码”长度要求6-18位"));
            }
            for (int j = 1; j < i; j++) {
              //判断用户编码是否重复
              String oldVcUserCode = StringUtils.trimToEmpty(ExcelUtil.getCellValue(sheet, j, 0, false)).replaceAll("\\s*", "");
              if ( !StringUtils.isBlank(userCode) && !StringUtils.isBlank(oldVcUserCode) &&  oldVcUserCode.equals(userCode) ) {
                needAdd = false;
                errorDatas.add( ExcelErrorData.getExcelErrorData(m, "与表格中第" + (j + 1) + "行存在相同[登录账号]"));
              }
            }
            User user = new User();
            user.setUserCode(userCode);
            user.setUserName(userName);
            user.setDepId(depId);
            user.setSalt(CryptoUtils.randomSalt());
            user.setUserPwd(userService.encryptPassword(user.getUserCode(), user.getUserPwd(), user.getSalt()));
            if (needAdd) {
              addUser.add(user);
            } else {
              jsonObject.setStatus(JSONObject.ERROR);
              jsonObject.setMsg("导入数据中存在异常信息");
            }

          }
          //根据这些来判断是否是中止导入还是跳过继续进行导入
          if (jsonObject.getStatus().equals(JSONObject.ERROR)  && !way) {
            jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
          } else {
            if (addUser.size() > 0) {
              try {
                userService.insertListUser(addUser);
                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                if ("导入成功".equals(jsonObject.getMsg())) {
                  jsonObject.setStatus(JSONObject.SUCCESS);
                }
              } catch (Exception e) {
                e.printStackTrace();
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("导入失败");
              }
            }
          }
        }
      }
    }
    jsonObject.setData(GsonUtil.toJson(errorDatas));
    return JSONObject.build(JSONObject.SUCCESS,jsonObject.getMsg(),errorDatas);
  }

  @RequestMapping("/updatePwd")
  @ResponseBody
  public JSONObject updatePwd(String userCode,String oldPassword, String newPassword){
     try {
       if(StringUtils.isEmpty(userCode)){
         return JSONObject.build(JSONObject.ERROR,"用户编码不能为空");
       }
       if(StringUtils.isEmpty(oldPassword)){
         return JSONObject.build(JSONObject.ERROR,"原有密码不能为空");
       }
       if(StringUtils.isEmpty(newPassword)){
         return JSONObject.build(JSONObject.ERROR,"新密码不能为空");
       }
       List<User> userList = userService.getUserCode(userCode);
       if(userList.isEmpty()){
         return JSONObject.build(JSONObject.ERROR,"用户不存在");
       }else{
         if(userList.size()!=1){
           return JSONObject.build(JSONObject.ERROR,"用户信息冲突");
         }else{
           User user = userList.get(0);
           String salt = user.getSalt();
           String userPwd = user.getUserPwd();
           if(userService.encryptPassword(userCode,oldPassword,salt).equals(userPwd)){
             String pwd = userService.encryptPassword(userCode,newPassword,salt);
             if(userPwd.equals(pwd)){
               return JSONObject.build(JSONObject.ERROR,"新旧密码不能一致");
             }
             user.setUserPwd(pwd);
             return userService.resetPwd(user);
           }else{
             return JSONObject.build(JSONObject.ERROR,"原密码有误");
           }
         }
       }
     }catch (Exception e){
       e.printStackTrace();
       throw new ParamsErrorException("系统出错");
     }

  }


}
